package com.study.system;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 客户端的IO处理
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<String>{

    //客户端的客户组
    private static ChannelGroup  channels= new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //客户端上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //把客户端加到通道组里
        channels.add(ctx.channel());
        //群发消息
        channels.writeAndFlush(ctx.channel().remoteAddress()+"欢迎来到聊天室！");

    }
    //客户端下线
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //群发消息
        channels.writeAndFlush(ctx.channel().remoteAddress()+"已离开聊天室！");

    }


    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("客户端收到数据：" + s);
    }
}
